import React, { useEffect, useState } from 'react';
import Taro  from '@tarojs/taro';
import { Button } from '@tarojs/components';
import request from '../../common/request';
import defaultHeaderPng from '../../assets/default_header.png';
import './index.scss';
// import { getImagePath } from '../../utils';
/*
*
* @ 自动设置头像
*
* */
const initImg =  Taro.getStorageSync("avatarUrl") || defaultHeaderPng;
function Index(props) {
  const [avatarUrl,setAvatarUrl] = useState(initImg);
  const { children, urlImg } = props;

  const updateAvatarUrl = (avatar) =>{
    setAvatarUrl(avatar);
    Taro.setStorageSync("avatarUrl", avatar);
  }

  // 用户点击头像后, 获取最新的头像
  const onGetUserInfo = (e) => {
    if (e.detail && e.detail.userInfo && e.detail.userInfo.avatarUrl) {
      console.log(e.detail.userInfo);
      const userInfo = e.detail.userInfo;
      // 保存头像
      request({method : 'POST', tartget: 'userInfoUpdate', data: { nickName: userInfo.nickName, avatar: userInfo.avatarUrl} })
      updateAvatarUrl(e.detail.userInfo.avatarUrl);
    }
    // const url =  e?.detail?.userInfo?.avatarUrl || avatarUrl;
    // Taro.previewImage({
    //   current: url,
    //   urls: [url],
    // });
  }

  // 本地没有头像，但是接口有头像，用接口的
  useEffect(()=>{
    if (!Taro.getStorageSync("avatarUrl") && urlImg) {
      setAvatarUrl(urlImg);
    }
  },[urlImg]);

  useEffect(()=>{
    /**
     * 获取用户信息
     */
    Taro.getUserInfo({
      success: function(res) {
        console.log(res);
        var userInfo = res.userInfo;
        // var nickName = userInfo.nickName
        updateAvatarUrl(userInfo.avatarUrl);
      },
      fail: function(res) {
        console.log(res);
      }
    })

    },[]);

  return (
    <Button style={{ border: 'none', display: 'flex', alignItems: 'center', padding: 0, margin: 0 }} plain hover-class='none' open-type='getUserInfo' onGetUserInfo={onGetUserInfo}>
      {
        React.cloneElement(children,{
          src:avatarUrl,
        })
      }
    </Button>
  );
}

export default Index;
